//
//  ProductTakePict.m
//  Trading365
//
//  Created by Jason on 12-3-20.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "ProductTakePict.h"
#import "InfoType.h"
#import "Type.h"
#import "FileUploader.h"
#import "RoundedRectImageCreater.h"
#import "Session.h"


@implementation ProductTakePict
@synthesize _uImage;
@synthesize _uName;
@synthesize _uActivityIndicator;
@synthesize caremaImage;
@synthesize myTitle;
@synthesize pictureBeginBlcok;
@synthesize pictureInfo;
@synthesize businessType,businessID,fileID;


- (void)initPictureBeginBlcok:(PictureBeginBlcok)pictureBeginBlcok1
{
    self.pictureBeginBlcok=pictureBeginBlcok1;
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    caremaflag = NO;
    self.title = INFO_STRING_PRODUCT_PICTURE_ADD;
    self.title = self.myTitle;   
    [self.view setBackgroundColor:BACKGROUND_COLOR];

    
    UIBarButtonItem *sButton = [[UIBarButtonItem alloc]
                                initWithTitle:@"保存" 
                                style:UIBarButtonItemStyleDone
                                target:self
                                action:@selector(savePic)];
    self.navigationItem.rightBarButtonItem = sButton;
    [sButton release];
    
//    UIBarButtonItem *bButton = [[UIBarButtonItem alloc]
//                                initWithTitle:@"返回" 
//                                style:UIBarButtonItemStyleDone
//                                target:self
//                                action:@selector(BackHome)];
//    self.navigationItem.leftBarButtonItem = bButton;
//    [bButton release];
    
    UIButton *barRetBut = [[UIButton alloc] initWithFrame:CGRectMake(5.0, 27.0, 50.0, 30.0)];
    [barRetBut setTitle:@" 返回" forState:UIControlStateNormal];
    UIFont *font              = [UIFont systemFontOfSize:14];
    barRetBut.titleLabel.font = font;
    UIImage *barRetImageNormal = [UIImage imageNamed:PIC_MAIL_SWITCH_SELF_NORMAL];
    [barRetBut setBackgroundImage:barRetImageNormal forState:UIControlStateNormal];
    UIImage *barRetImagePressed = [UIImage imageNamed:PIC_MAIL_SWITCH_SELF_PRESS];
    [barRetBut setBackgroundImage:barRetImagePressed forState:UIControlStateHighlighted];
    [barRetBut addTarget:self action:@selector(BackHome) forControlEvents:UIControlEventTouchUpInside];
    
    self.navigationItem.leftBarButtonItem  =  [[UIBarButtonItem alloc]initWithCustomView:barRetBut];
    
    [self takePicture:flagCameraPhotos];
    
}

- (void)viewDidUnload
{
    [self BackHome];
    
    [self set_uImage:nil];
    [self set_uName:nil];
    [self set_uActivityIndicator:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
    self.caremaImage = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark Image Picker delegate

- (UIImage *)scaleImage:(UIImage *)image toScale:(float)scaleSize
{
    UIGraphicsBeginImageContext(CGSizeMake(image.size.width*scaleSize,image.size.height*scaleSize));
    [image drawInRect:CGRectMake(0, 0, image.size.width * scaleSize, image.size.height *scaleSize)];
    UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    return scaledImage;
    //return image;
    //caremaImage = UIGraphicsGetImageFromCurrentImageContext();
    //return caremaImage;
}

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    pictureInfo = [[NSDictionary alloc] initWithDictionary:info];
    
    if (caremaflag == YES) {

//        UIImage *newImage = [RoundedRectImageCreater createRoundedRectImage:[info objectForKey:UIImagePickerControllerOriginalImage] size: [[info objectForKey:UIImagePickerControllerOriginalImage] size] ];
//        
//        UIImage *newImage1 = [[UIImage alloc] initWithCGImage:newImage.CGImage  scale:1.0 orientation:UIImageOrientationRight];
//        self._uImage.image=newImage1;
//        [newImage1 release];
        
        self._uImage.image=[RoundedRectImageCreater createRoundedRectImage:[info objectForKey:UIImagePickerControllerOriginalImage] size: [[info objectForKey:UIImagePickerControllerOriginalImage] size] ];
        caremaflag = NO;
    }else{
        //[self._uImage.image = [info objectForKey:UIImagePickerControllerOriginalImage];
        
        self._uImage.image = [RoundedRectImageCreater createRoundedRectImage:[info objectForKey:UIImagePickerControllerOriginalImage] size: [[info objectForKey:UIImagePickerControllerOriginalImage] size] ];
    }
    [picker dismissModalViewControllerAnimated:YES];
    
}

#pragma mark - text delegate
//该方法为点击输入文本框要开始输入是调用的代理方法：就是把view上移到能看见文本框的地方
- (void)textFieldDidBeginEditing:(UITextField *)textField{
    CGFloat keyboardHeight = 216.0f;
    if (self.view.frame.size.height - keyboardHeight <= textField.frame.origin.y + textField.frame.size.height) {
        CGFloat y = textField.frame.origin.y - (self.view.frame.size.height - keyboardHeight - textField.frame.size.height - 5);
        [UIView beginAnimations:@"srcollView" context:nil];
        [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
        [UIView setAnimationDuration:0.275f];
        self.view.frame = CGRectMake(self.view.frame.origin.x, -y, self.view.frame.size.width, self.view.frame.size.height);
        [UIView commitAnimations];
    }
}

//该方法为点击虚拟键盘Return，要调用的代理方法：隐藏虚拟键盘
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return YES;
}

//该方法为完成输入后要调用的代理方法：虚拟键盘隐藏后，要恢复到之前的文本框地方
- (void)textFieldDidEndEditing:(UITextField *)textField{
    [UIView beginAnimations:@"srcollView" context:nil];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    [UIView setAnimationDuration:0.275f];
    self.view.frame = CGRectMake(self.view.frame.origin.x, 0, self.view.frame.size.width, self.view.frame.size.height);
    [UIView commitAnimations];
    
    [textField resignFirstResponder];
}

-(void)textViewDidEndEditing:(UITextView *)textView
{
    [textView resignFirstResponder];
    
}

-(BOOL) textViewShouldReturn:(UITextView *)textView
{
    [textView resignFirstResponder];
    return YES;
}

#pragma mark - UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)modalView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    int type=buttonIndex;
    if ([[InfoType share] IsSimulator])
        type = 1;
   
    [self takePicture:type];
}


#pragma mark - my fun

-(void)setFlagCameraPhotos:(int)type
{
    flagCameraPhotos = type;
}

- (IBAction)reCameraPick:(id)sender {
//    [self cameraPick];
    
    [self takePicture:flagCameraPhotos];    
}

-(void) takePicture:(int)type
{
    CGRect frame = self.view.superview.frame;
    CGFloat offset = self.tabBarController.tabBar.frame.size.height;
    frame.size.height += offset;
    self.view.frame = frame;
    heightflag = 49;

    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.delegate = (id)self;
    picker.allowsEditing = YES;
    
    if (type == 0){
        caremaflag = YES;
        picker.sourceType = UIImagePickerControllerSourceTypeCamera;
    }
    if (type == 1){
        picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    }
    //picker.vedioQuality = UIImagePickerControllerQualityType640x480;
    [self presentModalViewController:picker animated:YES];
    [picker release];
    
}

-(void) cameraPick
{
    //[self.tabBarController setHidesBottomBarWhenPushed:YES];
    CGRect frame = self.view.superview.frame;
    CGFloat offset = self.tabBarController.tabBar.frame.size.height;
    frame.size.height += offset;
    self.view.frame = frame;
    heightflag = 49;
    caremaflag = YES;
    
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.delegate = (id)self;
    picker.allowsEditing = YES;
    picker.sourceType = UIImagePickerControllerSourceTypeCamera;
    //picker.vedioQuality = UIImagePickerControllerQualityType640x480;
    [self presentModalViewController:picker animated:YES];
    [picker release];
    
}
//保存的相片
-(void)photosAlbumPick
{
    CGRect frame = self.view.superview.frame;
    CGFloat offset = self.tabBarController.tabBar.frame.size.height;
    frame.size.height += offset;
    self.view.frame = frame;
    heightflag = 49;
    caremaflag = YES;
    
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.delegate = (id)self;
    picker.allowsEditing = YES;
    picker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
    //picker.vedioQuality = UIImagePickerControllerQualityType640x480;
    [self presentModalViewController:picker animated:YES];
    [picker release];
   
}

-(void) photoLibraryPick
{
    CGRect frame = self.view.superview.frame;
    CGFloat offset = self.tabBarController.tabBar.frame.size.height;
    frame.size.height += offset;
    self.view.frame = frame;
    heightflag = 49;
    caremaflag = YES;
    
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.delegate = (id)self;
    picker.allowsEditing = YES;
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    [self presentModalViewController:picker animated:YES];
    [picker release];   
}

- (void)savePic {
    //Save Pic
    if (self.pictureBeginBlcok != nil) {
        self.pictureBeginBlcok(pictureInfo,flagCameraPhotos);
    }
    
    NSString *fileName=@"";
    if (_uName.text.length > 0 )
        fileName = _uName.text;
    
    //保存上传
    FileUploader* imup = [[FileUploader alloc] init];
    [imup uploadPic:self._uImage.image delegate:self businessType:businessType 
         businessID:businessID fileType:@"jpg" fileName:fileName memberID:[[Session share] getMemberID]];
    [imup release];
    
    [[InfoType share] SetFlagFreshView:INFO_TYPE_VIEW_REFRESH];

    [self BackHome];
    
    //self._uImage.image;
}

-(void)BackHome{
    
    if (heightflag == 49) {
        CGRect frame = self.view.superview.frame;
        frame.size.height = 480.0f;    //offset is 49.0
        //NSLog(@"%f",frame.size.height);
        self.view.frame = frame;
        heightflag = 50;
    }
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)dealloc {
    [pictureInfo release];
    [myTitle release];
    [_uImage release];
    [_uName release];
    [_uActivityIndicator release];
    [businessType release];
    [businessID release];
    [fileID release];
    
    [super dealloc];
}

- (void)uploadedImage:(NSString*)URL sender:(FileUploader*)sender
{
    NSLog(@"url:%@",URL);
    if (URL != nil) {
        NSLog(@"it is upload suc");
    }
    //[self._uActivityIndicator stopAnimating];
}

@end
